"use strict";
let $http = require("axios");
// let sql = require('mssql');
let CFG = require("./config");
// const db = require('./db');
// const api = 'http://172.16.7.20:8668/app_api/v3/';
const api = 'http://api.zymk.cn/app_api/v3/';
const tagColors = ["#c78590", "#f3bd7e", "#6ec4e9", "#66c9bb", "#9b9bd5"]
String.prototype.FilterHtml = function() {
  return this.replace(/<\/?[a-z][^<>]*>/ig, "").replace(/&[a-z]+;/gi, "");
};
String.prototype.format = function() {
  var a = arguments;
  return this.replace(/{(\d+)}/g, function(m, i) {
    return a[i];
  });
};
String.prototype.padLeft = function(padchar, num) {
  return padchar.repeat(this.length > num ? 0 : num - this.length) + this;
};

// 对数据进行转换
const getStringByLongNumber = (number) => {
  let result = '';
  if(number < 10000) {
    result = number;
  } else if(number < 100000000) {
    result = (number / 10000).toFixed(1) + '万';
  } else {
    let tmp = parseInt(number / 100000000, 10);
    result = tmp + '亿' + parseInt((number - tmp * 100000000) / 10000) + '万';
  }
  return result;
}

const formatDate = (date, fmt) => {
  date = new Date(date);
  if(/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }

  for(var i in o) {
    if(new RegExp('(' + i + ')').test(fmt)) {
      var str = o[i] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1 ? str : str.padLeft('0', 2)));
    }
  }
  return fmt;
}

const getTimeSpan = (data, closer) => {
  data = parseInt(data, 10);
  let getTimepan = parseInt((new Date().getTime() - data) / 1000);
  let day = Math.floor(getTimepan / 86400);
  let hour = Math.floor((getTimepan - day * 86400) / 3600);
  let minute = Math.floor((getTimepan - day * 86400 - hour * 3600) / 60);
  let second = Math.floor(getTimepan - day * 86400 - hour * 3600 - minute * 60);
  let str = '';
  if(closer) {
    if(day > 9) {
      return this.formatDate(data, 'yyyy.MM.dd') + '日';
    }
    if(day > 0) {
      return day + '天前';
    }
    if(hour > 0) {
      return hour + '小时前';
    }
    if(minute > 0) {
      return minute + '分钟前';
    }
    return '1分钟内';
  } else {
    return formatDate(data, 'yyyy-MM-dd');
  }
}

const swipeImgInit = (res, imgUrl) => {
  let arr = [];
  res.forEach((v, i) => {
    let obj = {};
    obj["src"] = pathInit("news", v.id, imgUrl);
    if(/^(https?\:)/.test(v.comic_id)) {
      obj["isFlag"] = false;
    } else {
      obj["isFlag"] = true;
    }
    obj["url"] = v.comic_id;
    obj["desc"] = v.slide_desc;
    arr.push(obj);
  });
  return arr;
};

const rankListInit = (data, imgUrl) => {
  data.forEach((v, i) => {
    v["src"] = pathInit(v.comic_id, imgUrl);
  });
  return data;
};
// 路径初始化
const pathInit = (id, imgUrl) => {
  if(id) {
    let path = (imgUrl + "").format(getPathById(id));
    return path;
  }
};
const tabInit = data => {
  let arr = [];
  data.forEach((v, k) => {
    arr.push(v.sort_group);
  });
  return arr;
};
const classImg = (data, imgUrl) => {
  data.forEach(item => {
    item.data.forEach(v => {
      v["src"] = pathInit(v.id, imgUrl);
    });
  });
  return data;
};
const homeImg = (data, imgUrl) => {
  data.forEach(item => {
    item.data.forEach(v => {
      v["src"] = pathInit(v.comic_id, imgUrl);
      v.score = (v.score / 10).toFixed(1);
    });
  });
  return data;
};
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
// 根据数字id生成文件路径，补齐至9位后每3位数字一级目录
// 例如：id为12345，则文件路径为000/012/345

const getPathById = id => {
  var id = (id || 0).toString().padLeft("0", 9);
  var result = "";
  while(id.length > 3) {
    result = "/" + id.slice(-3) + result;
    id = id.slice(0, id.length - 3);
  }
  if(id) {
    result = id + result;
  }
  return result;
};
const score = data => {
  data.forEach(v => {
    v.score = (v.score / 10).toFixed(1);
  })
  return data
}
const getCharcode = (x, y) => {
  return encodeURIComponent(x.toUpperCase()).replace(/./g, function(a) {
    return String.fromCharCode(a.charCodeAt(0) + y % 10)
  }).replace(/([\\"'])/g, "\\$1");
}
module.exports = {
  //首页
  home: async ctx => {
    let data = {};
    let s = Date.now()
      // 获得推荐
    await $http.get(api + 'getconfig/')
      .then(res => {
        let config = {}
        if(res.status === 200) {
          config = res.data.data
          return $http.get(api + 'getrecommend/')
            .then(res => {
              if(res.status === 200) {
                data = {
                  book: homeImg(res.data.data.book, config.coverpath),
                  swiper: swipeImgInit(res.data.data.slide_list, config.bannerpath),
                  hot_List: rankListInit(res.data.data.hot_list, config.coverpath),
                  month_ticket_list: rankListInit(res.data.data.month_ticket_list, config.coverpath),
                  gold_list: rankListInit(res.data.data.gold_list, config.coverpath)
                }
              }
            })
        }
      }, err => {
        console.log('error!!!!!!')
      })
    console.log(`whole request: ${Date.now() - s}ms`)
    await ctx.render('default/index', {
      title: 'title is search',
      body: 'this is search.',
      data: data,
      tabs: ['人气榜', '打赏榜', '月票榜']
    });
  },

  detail: async ctx => {
    let id = ctx.params.id;
    let data = {};
    let relation_list = [];
    let cover = '';
    let authorAvatar = '';
    await $http.get(api + 'getconfig/')
      .then(res => {
        let config = {}
        if(res.status === 200) {
          config = res.data.data;
          return $http.get(api + 'getcomicinfo/?comic_id=' + id)
            .then(res => {
              if(res.status === 200) {
                data = res.data.data;
                data.score = (data.score / 10).toFixed(1);
                data.update_time_span = getTimeSpan(data.update_time, false);
                data.comic_type.forEach((item, idx) => {
                  item['bg'] = tagColors[idx % tagColors.length]
                })
                data.total_click = getStringByLongNumber(data.total_click);
                data.fans_hot.forEach(item => {
                  item['head'] = pathInit(item.id, config.headpath);
                });
                data.fans_gold.forEach(item => {
                  item['head'] = pathInit(item.id, config.headpath);
                });
                relation_list = rankListInit(res.data.data.relation_list, config.coverpath);
                cover = pathInit(res.data.data.comic_id, config.coverpath);
                authorAvatar = pathInit(res.data.data.author_info.Uid, config.headpath);
              }
            })

        }
      })
    await ctx.render('default/detail', {
      data,
      relation_list,
      cover,
      authorAvatar,
      tab: ['详情', '目录', '支持'],
      tagColors
    });
  },
  class: async ctx => {
    let data = {};
    await $http.get(api + "getconfig/").then(res => {
      if(res.status === 200) {
        data = {
          tabtitle: tabInit(res.data.data.comic_type),
          comic_type: classImg(res.data.data.comic_type, res.data.data.sortpath)
        };
      }
    });
    await ctx.render("default/class", {
      data
    });
  },
  sort: async ctx => {
    let data = {};
    let id = ctx.params.id || '';
    let keyword = ctx.params.keyword || '';
    let sort = ctx.params.sort;
    let page = ctx.params.page;
    let title = ctx.params.name || '';
    let by = ctx.params.by;
    console.log(id)
    await $http.get(api + "getconfig/").then(res => {
      let config = {};
      if(res.status === 200) {
        config = res.data.data;
        if(id) {
          return $http.get(api + "getsortlist/?type=" + id + '&sort=' + sort + '&page=' + page).then(res => {
            data = {
              title: title,
              data: score(rankListInit(res.data.data.page.comic_list, config.coverpath)),
              by: by,
              id: id,
              coverpath: config.coverpath,
              total_page: res.data.data.page.total_page
            }
          });
        }
        if(keyword) {
          return $http.get(api + "getsortlist/?key=" + keyword + '&sort=' + sort + '&page=' + page).then(res => {
            data = {
              title: title,
              data: score(rankListInit(res.data.data.page.comic_list, config.coverpath)),
              by: by,
              keyword: keyword,
              coverpath: config.coverpath,
              total_page: res.data.data.page.total_page
            }
          });
        }
      }
    });
    await ctx.render("default/sort", {
      data,
      order: [{
          key: 'click',
          value: '人气'
        },
        {
          key: 'score',
          value: '评分'
        },
        {
          key: 'date',
          value: '更新'
        },
      ],
    })
  },
  book: async ctx => {
    let data = {};
    let id = ctx.params.id;
    let name = ctx.params.name;
    await $http.get(api + "getconfig/").then(res => {
      let config = {};
      if(res.status === 200) {
        config = res.data.data;
        return $http.get(api + 'getbookinfo/?book_id=' + id).then(res => {
          if(res.status === 200) {
            data = res.data.data;
            data['cover_path'] = pathInit(id, config.bookpath)
            data.book_list.forEach(item => {
              item['src'] = pathInit(item.comic_id, config.coverpath);
              item.score = (item.score / 10).toFixed(1);
            })
          }
        })
      }
    })
    await ctx.render('default/book', {
      data
    })
  },
  personalset: async ctx => {
    await ctx.render('default/personalset');
  },
  bindAccount: async ctx => {
    await ctx.render('default/bindAccount');
  },
  read: async ctx => {
    let {
      comic_id,
      chapter_id
    } = ctx.params;
    let data = {};
    await $http.get(api + "getconfig/").then(res => {
      if(res.status === 200) {
        let config = res.data.data;
        return $http.get(api + "getcomicinfo/?comic_id=" + comic_id).then(res => {
          if(res.status === 200) {
            let tmpobj = {};
            tmpobj = res.data.data
            tmpobj.chapter_list.forEach(v => {
              if(v.chapter_id == chapter_id) {
                v.chapter_addr = getCharcode(v.chapter_addr, chapter_id);
                v['comic_name'] = tmpobj.comic_name;
                v['readmode'] = 1;
                v['maxpreload'] = 5;
                v['defaultminline'] = 1;
                v['domain'] = config.comicdomain;
                v['comic_size'] = config.comic_definition.middle;
                let index = tmpobj.chapter_list.indexOf(v);
                let nextChapter = [];
                if(index === 0) {
                  v['nextid'] = '';
                  v['nextname'] = '';
                } else {
                  nextChapter = tmpobj.chapter_list[index - 1];
                  v['nextid'] = nextChapter.chapter_id;
                  v['nextname'] = nextChapter.chapter_name;
                }
                data = v
              }
            })
          }
        })
      }
    })
    await ctx.render('default/read', {
      data: JSON.stringify(data)
    });
  },
  search: async ctx => {
    let hotSearch = {};
    await $http.get(api + 'gethotsearch/')
      .then(res => {
        if(res.status == 200) {
          hotSearch = res.data.data.list
        }
      })
      .catch(error => {
        console.log(error)
      })
    await ctx.render('default/search', {
      hotSearch,
      tagColors: ["#c78590", "#f3bd7e", "#6ec4e9", "#66c9bb", "#9b9bd5"]
    });
  },
  discovery: async ctx => {
    let discoverypage = {};
    await $http.get(api + 'getconfig/')
      .then(res => {
        if(res.status == 200) {
          discoverypage = res.data.data.discoverypage
        }
      })
      .catch(error => {
        console.log(error)
      })
    await ctx.render('default/discovery', {
      discoverypage
    });
  },
  mine: async ctx => {
    await ctx.render('default/mine', {
      menus: [{
          title: '充值中心',
          name: 'pay',
          tips: '充点元宝，解锁新章节哦~'
        },
        {
          title: '使用帮助',
          name: 'help',
          tips: '找编辑mm么么哒~.~'
        },
        {
          title: '反馈报错',
          name: 'feedback',
          tips: '为你变好棒棒哒=.='
        }
      ]
    });
  },
  help: async ctx => {
    let helpList = {};
    await $http.get(api + 'gethelplist/')
      .then(res => {
        if(res.status == 200) {
          let tmpData = res.data.data;
          tmpData.forEach(item => {
            item.flag = false;
            item.help_content = null;
          });
          helpList = tmpData;
        }
      })
      .catch(error => {
        console.log(error)
      })
    await ctx.render('default/help', {
      helpList
    });
  },
  login: async ctx => {
    await ctx.render('default/login');
  },
  bindpage: async ctx => {
    let type = ctx.params.type;
    await ctx.render('default/bindpage', { type });
  },
  modifypage: async ctx => {
    let type = ctx.params.type;
    await ctx.render('default/modifypage', { type });
  },
  record_list: async ctx => {
    await ctx.render('default/record_list');
  }
};